package com.central.apps.controller;

import com.central.app.service.FlowCommonService;
import com.central.app.service.HandlerService;
import com.central.apps.entity.BizFlowConsult;
import com.central.apps.entity.BizFlowCountersign;
import com.central.apps.service.CustomizationService;
import com.central.common.web.PageResult;
import com.central.common.web.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

@Slf4j
@RestController
@Api(tags = "客户化处理层")
@RequestMapping("/customization")
public class CustomizationController {

	@Autowired
	private CustomizationService customizationService;
    @Autowired
    private FlowCommonService flowCommonService;
    @Autowired
    private HandlerService handlerService;

    @ApiOperation(value = "查询设备分类下的技术参数")
    @GetMapping("/findTechnicalByEquipment/{equipmentclassify}")
    public List<Map<String,Object>> findTechnicalByEquipment(@PathVariable String equipmentclassify) {
        StringBuffer sbf = new StringBuffer("select * from bl_technicaldata t LEFT JOIN bl_equipmentclassify e ON t.equipmentclassify = e.equipmentclassify  LEFT JOIN bl_equipmentclassify ee ON  t.equipmentclassify = ee.equipmentclassify  where (e.equipmentclassify = '" + equipmentclassify + "' or ee.pequipmentclassify = '" + equipmentclassify + "')");
        List<Map<String,Object>> returnList = handlerService.findBySql(sbf.toString());
        return returnList;
    }
    @ApiOperation(value = "删除当前设备的所有技术参数")
    @DeleteMapping("/deleteTechnicalspecificationByAssetnum/{assetnum}")
    public Result deleteTechnicalspecificationByAssetnum(@PathVariable String assetnum) {
        StringBuffer sbf = new StringBuffer("delete from bl_technicalspecification where assetnum = '" + assetnum + "'");
        handlerService.findBySql(sbf.toString());
        handlerService.updateBySql("UPDATE bl_asset set equipmentclassify = null where assetnum = '" + assetnum + "'");
        return Result.succeed("操作成功");
    }

    @ApiOperation(value = "查预防性维护的子表信息")
    @PostMapping("/findPmLineByPmnum")
    public PageResult<Map<String,Object>> findPmLineByPmnum(@RequestBody Map<String, Object> params) throws Exception {
        String deptcode = MapUtils.getString(params,"deptcode");
        String month = MapUtils.getString(params,"month");
        String assetnum = MapUtils.getString(params,"assetnum");
        String assetdecs = MapUtils.getString(params,"asserdesc");
        String content = MapUtils.getString(params,"content");

        StringBuffer sbf = new StringBuffer("select '定期维护' as fixtype ,p.location,location.description as locationDesc,a.description,p.assetnum,p.description as  asserdesc,l.* from bl_pmline l LEFT JOIN bl_pm p ON l.pmnum = p.pmnum LEFT JOIN bl_locationmanagement location ON p.location = location.location LEFT JOIN bl_asset a ON a.assetnum = p.assetnum where 1=1 ");
        if(StringUtils.isNotBlank(deptcode)){
            sbf.append(" and  LEFT(l.deptcode,6)=LEFT('"+deptcode+"',6)");
        }
        if(StringUtils.isNotBlank(month)){
            sbf.append(" and l.`month` like '%" + month + "%' ");
        }
        if(StringUtils.isNotBlank(assetnum)){
            sbf.append(" and p.assetnum like '%" + assetnum + "%' ");
        }
        if(StringUtils.isNotBlank(assetdecs)){
            sbf.append(" and p.description like '%" + assetdecs + "%' ");
        }
        if(StringUtils.isNotBlank(content)){
            sbf.append(" and l.content like '%" + content + "%' ");
        }
        PageResult<Map<String,Object>> returnList = customizationService.findPage(params, sbf.toString());
        return returnList;
    }

    @ApiOperation(value = "根据表名修改单个或多个字段字段")
    @PostMapping("/updateTableByColumn/{table}")
    public Result updateTableByColumn(@PathVariable String table, @RequestBody Map<String, Object> params) {
        Long id = MapUtils.getLong(params,"id");
        if(ObjectUtils.isNotEmpty(id)){
            params.remove("id");
            StringJoiner sj = new StringJoiner(",");
            for (String key : params.keySet()){
                Object value = params.get(key);
                String slq = "'" + value + "'";
                if(ObjectUtils.isEmpty(value)){
                    slq = null;
                }
                sj.add(key + " = " + slq );
            }
            handlerService.updateBySql("update " + table + " set " + sj + " where id = " + id);
        }else{
            return Result.failed(params,"操作失败 没有id！！！");
        }
        return Result.succeed(params,"操作成功");
    }


    @ApiOperation("{app}单据流程状态")
    @GetMapping({"{app}/flow/workStatus/{id}"})
    public Result workStatus(@PathVariable String app, @PathVariable Long id) throws Exception {
        int type =0; //0:流程未启动。1:流程进行中。2:流程已结束。3:当前流程执行人。4不是当前流程执行人 （3和4流程都未结束）
        boolean start = flowCommonService.isStart(app,id);
        if(!start){
            return Result.succeed(type, "流程未启动");
        }
        //是否结束
        boolean end = flowCommonService.isEnd(app,id);
        if(end) {
            type = 2;
            return Result.succeed(type, "流程已结束");
        }
        //是否是执行人
        boolean execute = flowCommonService.isExecute(app,id);
        if(!execute) {
            type = 4;
            return Result.succeed(type, "您不是当前流程执行人");
        }else{
            type = 3;
            return Result.succeed(type, "当前流程执行人");
        }
    }

    @ApiOperation(value = "查询PC端拥有流程的应用")
    @PostMapping("/selectPcAppByflow")
    public Result selectPcAppByflow() throws Exception{
        List<Map<String, Object>> bySql = handlerService.findBySql("SELECT description FROM biz_app WHERE flowkey IS NOT NULL");
        return Result.succeedWith(bySql,0,"操作成功");
    }

    @ApiOperation(value = "设置会签节点审批人")
    @PostMapping("/setCountersign")
    public Result setCountersign(@RequestBody BizFlowCountersign bizFlowCountersign) {
        try {
            customizationService.setCountersign(bizFlowCountersign);
        } catch (Exception e) {
            return Result.succeed("设置会签异常");
        }
        return Result.succeed(bizFlowCountersign,"设置会签成功");
    }

    @ApiOperation(value = "设置意见征询")
    @PostMapping("/setConsult")
    public Result setConsult(@RequestBody BizFlowConsult bizFlowConsult) {
        try {
            customizationService.setConsult(bizFlowConsult);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
        return Result.succeed(bizFlowConsult,"设置意见征询成功");
    }

    @ApiOperation(value = "获取意见征询")
    @GetMapping("/getConsult")
    public Map<String, Object> getConsult(String app, Long id) throws Exception {
        return customizationService.getConsult(app, id);
    }

    @ApiOperation(value = "查找下一个代理人类型")
    @PostMapping("/getAgentType")
    public Result getAgentType(@RequestBody Map<String, Object> params) {
        try {
            return Result.succeed(customizationService.getAgentType(params), "查找下一个代理人类型成功");
        } catch (Exception e) {
            return Result.succeed("查找下一个代理人类型失败");
        }
    }

    @ApiOperation(value = "查找当前代理人类型")
    @PostMapping("/getCurrentAgentType")
    public Result getCurrentAgentType(@RequestBody Map<String, Object> params) {
        try {
            return Result.succeed(customizationService.getCurrentAgentType(params), "查找当前代理人类型成功");
        } catch (Exception e) {
            return Result.succeed("查找当前代理人类型失败");
        }
    }

    @SneakyThrows
    @ApiOperation(value = "判断意见征询是否完成")
    @PostMapping("/judgeConsultFinished")
    public Result judgeConsultFinished(@RequestBody Map<String, Object> params) {
        boolean bool = customizationService.judgeConsultFinished(params);
        return Result.succeed(String.valueOf(bool));
    }

    @ApiOperation(value = "更新意见征询配置信息")
    @PostMapping("/updateConsultInfo")
    public Result updateConsultInfo(@RequestBody Map<String, Object> params) {
        try {
            customizationService.updateConsultInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("更新意见征询配置信息异常");
        }
        return Result.succeed("更新意见征询配置信息成功");
    }

    @ApiOperation("{app}单据流程状态")
    @GetMapping({"{app}/flow/btnJudgeLogic/{id}"})
    public Map<String, Object> btnJudgeLogic(@PathVariable String app, @PathVariable Long id) {
        try {
            return customizationService.btnJudgeLogic(app, id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @SneakyThrows
    @ApiOperation(value = "判断意见征询执行人是否删除")
    @PostMapping("/judgeConsultExecutors")
    public Result judgeConsultExecutors(@RequestBody Map<String, Object> params) {
        String result = customizationService.judgeConsultExecutors(params);
        return Result.succeed(result);
    }

    @SneakyThrows
    @ApiOperation(value = "根据部门树过滤数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "app", value = "应用名称", required = true, dataType = "String")})
    @PostMapping("{app}/findDepts")
    public PageResult<Map<String,Object>> findList(@PathVariable String app, @RequestBody Map<String, Object> params) {
        return customizationService.findList(app, params);
    }
}
